Variables
- In programming, data that can be used and altered throughout a program is stored in variables.
- These are designated memory areas where you can put variables that vary while the program executes.
- Variables in C++ require declaration before they can be utilized; this declaration must include the variable name and data type.
❑ Following rules must be followed for
identifiers:
⮚ The
first character must always be an alphabet or an underscore.
⮚ It
should be formed using only letters, numbers, or underscore.
⮚ uppercase and lowercase are distinct
⮚ A
keyword cannot be used as a variable name.
⮚ It
should not contain any whitespace character.
⮚ The
name must be meaningful.
Declaring the variable
To create a variable,
you must specify the data type and assign it a value:
Syntax
Data Type variable = value;
Example 1: Basic Variable Declaration and Initialization
#include <iostream>
using namespace std;
int main() {
// Declare an integer variable
int age = 25; // 'age' is a meaningful name for a variable that stores an age
// Declare a double variable
double price = 19.99; // 'price' clearly indicates that this variable holds a price value
// Output the values of the variables
cout << "Age: " << age << endl;
cout << "Price: " << price << endl;
return 0;
}
Example 2: Using Variables in Calculations
0 Comments